package com.example.yunpicture.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yunpicture.annotation.AuthCheck;
import com.example.yunpicture.common.BaseResponse;
import com.example.yunpicture.common.DeleteRequest;
import com.example.yunpicture.common.ResultUtils;
import com.example.yunpicture.constant.UserConstant;
import com.example.yunpicture.exception.BusinessException;
import com.example.yunpicture.exception.ErrorCode;
import com.example.yunpicture.exception.ThrowUtils;
import com.example.yunpicture.manager.auth.SpaceUserAuthManager;
import com.example.yunpicture.model.dto.space.SpaceAddRequest;
import com.example.yunpicture.model.dto.space.SpaceEditRequest;
import com.example.yunpicture.model.dto.space.SpaceQueryRequest;
import com.example.yunpicture.model.dto.space.SpaceUpdateRequest;
import com.example.yunpicture.model.entity.Space;
import com.example.yunpicture.model.entity.User;
import com.example.yunpicture.model.vo.SpaceVO;
import com.example.yunpicture.service.SpaceService;
import com.example.yunpicture.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Log4j2
@RestController
@RequestMapping("/space")
//@Api(tags = "空间操作接口")
public class SpaceController {

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 创建空间
     * @param spaceAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    //@ApiOperation("创建空间")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest,HttpServletRequest request){
        //1.校验参数
        ThrowUtils.throwif(spaceAddRequest==null,ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        //2.添加
        long spaceId = spaceService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(spaceId);
    }

    /**
     * 删除空间
     */
    @PostMapping("/delete")
    //@ApiOperation("删除空间")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Space space = spaceService.getById(id);
        ThrowUtils.throwif(space == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = spaceService.removeById(id);
        ThrowUtils.throwif(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * "更新空间（仅管理员可用）
     * @param spaceUpdateRequest
     * @return
     */

    @PostMapping("/update")
    //@ApiOperation("更新空间（仅管理员可用）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest){
        //1.校验参数
        ThrowUtils.throwif(spaceUpdateRequest==null||spaceUpdateRequest.getId()<=0,ErrorCode.PARAMS_ERROR);
        //2.将dto转化为实体类
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest,space);
        //3.自动填充空间级别对应的空间参数
        spaceService.fillSpaceBySpaceLevel(space);
        //4.校验空间是否正确
        spaceService.validSpace(space,false);
        //5.判断空间是否存在
        Space oldSpace = spaceService.getById(spaceUpdateRequest.getId());
        ThrowUtils.throwif(oldSpace==null,ErrorCode.NOT_FOUND_ERROR);
        //6.操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwif(!result,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取空间（仅管理员可用）
     */
    @GetMapping("/get")
    //@ApiOperation("根据 id 获取空间（仅管理员可用）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(long id) {
        ThrowUtils.throwif(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtils.throwif(space == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(space);
    }

    /**
     * 根据 id 获取空间（封装类）
     */
    @GetMapping("/get/vo")
    //@ApiOperation("根据 id 获取空间（所有人）")
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwif(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtils.throwif(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(space);
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(spaceVO);
    }

    /**
     * 分页获取空间列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    //@ApiOperation("分页获取空间列表（仅管理员可用）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spacePage);
    }

    /**
     * 分页获取空间列表（封装类）
     */
    @PostMapping("/list/page/vo")
    //@ApiOperation("分页获取空间列表（所有人）")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwif(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        // 获取封装类
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage));
    }


    /**
     * 编辑空间（给用户使用）
     */
    @PostMapping("/edit")
    //@ApiOperation("编辑空间（给用户使用）")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        //1.校验参数
        if (spaceEditRequest == null || spaceEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.在此处将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest,space);
        //3.自动填充参数
        spaceService.fillSpaceBySpaceLevel(space);
        //4.设置编辑时间
        space.setEditTime(new Date());
        //5.校验空间
        spaceService.validSpace(space,false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        Long id = spaceEditRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwif(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldSpace.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwif(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


}
